<template>
  <div class="demo">
    <div class="demo-title">手动上传</div>
    <div class="demo-content">
      <Upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove">
        <Button><UploadOutlined />Select File</Button>
      </Upload>
      <Button
        type="primary"
        :disabled="fileList?.length === 0"
        :loading="uploading"
        style="margin-top: 16px"
        @click="handleUpload"
      >
        {{ uploading ? 'Uploading' : 'Start Upload' }}
      </Button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import request from 'umi-request';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import Message from '@sscd/message';
  import Button from '@sscd/button';
  import Upload from '@sscd/upload';
  import type { UploadProps } from '@sscd/upload';
  const fileList = ref<UploadProps['fileList']>([]);
  const uploading = ref<boolean>(false);
  const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = fileList.value?.indexOf(file);
    const newFileList = fileList.value?.slice();
    newFileList?.splice(index as number, 1);
    fileList.value = newFileList;
  };
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    fileList.value = [...fileList.value, file];
    return false;
  };
  const handleUpload = () => {
    const formData = new FormData();
    fileList.value?.forEach((file: UploadProps['fileList'][number]) => {
      formData.append('files[]', file as any);
    });
    uploading.value = true;
    // You can use any AJAX library you like
    request('https://www.mocky.io/v2/5cc8019d300000980a055e76', {
      method: 'post',
      data: formData,
    })
      .then(() => {
        fileList.value = [];
        uploading.value = false;
        Message.success('upload successfully.');
      })
      .catch(() => {
        uploading.value = false;
        Message.error('upload failed.');
      });
  };
</script>
